import { _decorator, Component, find, Node, tween, Vec3, EventTouch, director, UITransform, view, Camera, Sprite, Color } from 'cc';
import { BaseMoveCommand } from './BaseMoveCommand';
import { IGuideData } from './IGuideData';
import { BaseGuideCommand } from './BaseGuideCommand';
const { ccclass, property } = _decorator;

/**
 * 滑动动画命令
 */
@ccclass('SwipeMoveGuideCommand')
export class SwipeMoveGuideCommand extends BaseGuideCommand {
    private startTouchPos: Vec3 | null = null;
    private resolve!: () => void;
    private reject!: (reason?: any) => void;
    private timeoutId?: number;
    private startPos: Vec3;
    private endPos: Vec3;
    private touchListenerNode: Node | null = null;
    private rangeDisplayNode: Node | null = null;

    protected async run(): Promise<void> {
        console.log("【SwipeMoveGuideCommand】执行...");
        // 获取当前的小时、分钟和秒数
        const now = new Date();
        const hours = now.getHours();
        const minutes = now.getMinutes();
        const seconds = now.getSeconds();

        // 打印当前时间（时:分:秒）
        console.log(`输出当前时间： ${hours}:${minutes}:${seconds}`);

        return new Promise((resolve, reject) => {
            this.resolve = resolve;
            this.reject = reject;

            let targetNode = find(this.stepConfig.path);

            this.endPos = new Vec3(targetNode.position.x, targetNode.position.y, 0);
            this.startPos = new Vec3(this.guideNode.position.x, this.guideNode.position.y, 0);

            this.curTween = tween(this.guideNode)
               .to(this.stepConfig.duration, { position: this.endPos })
               .to(this.stepConfig.duration / 5, { position: this.startPos })
               .union()
               .repeatForever()
               .start();

            this.setupTouchListener();
            this.drawRangeDisplay();

            this.timeoutId = setTimeout(() => {
                this.cleanup();
                reject(new Error(`滑动操作超时：${this.stepConfig.path}`))
            }, this.stepConfig.waitForSecond * 1000);
        });
    }

    private setupTouchListener() {
        // 创建一个全屏的透明节点用于监听触摸事件
        this.touchListenerNode = new Node("TouchListener");
        const uiTransform = this.touchListenerNode.addComponent(UITransform);
        const winSize = view.getVisibleSize();
        uiTransform.setContentSize(winSize.width, winSize.height);
        this.touchListenerNode.setPosition(0, 0);
        this.guideNode.getParent()?.addChild(this.touchListenerNode);

        this.touchListenerNode.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.touchListenerNode.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    private getCamera(): Camera | null {
        const scene = director.getScene();
        if (scene) {
            const cameraNode = scene.getChildByPath('Canvas/Camera'); // 假设相机节点名为 Main Camera
            if (cameraNode) {
                return cameraNode.getComponent(Camera);
            }
        }
        return null;
    }

    private onTouchStart(event: EventTouch) {
        const camera = this.getCamera();
        if (camera) {
            const touchPos = camera.screenToWorld(new Vec3(event.getLocationX(), event.getLocationY(), 0));
            if (this.isInRange(touchPos, this.startPos, this.endPos)) {
                this.startTouchPos = touchPos;
            }
        }
    }

    private onTouchEnd(event: EventTouch) {
        if (this.startTouchPos) {
            const camera = this.getCamera();
            if (camera) {
                const endTouchPos = camera.screenToWorld(new Vec3(event.getLocationX(), event.getLocationY(), 0));
                const distance = Vec3.distance(this.startTouchPos, endTouchPos);
                // 可以适当调整滑动距离的阈值
                if (distance > 5 && this.isInRange(endTouchPos, this.startPos, this.endPos)) {
                    const dx = endTouchPos.x - this.startTouchPos.x;
                    const dy = endTouchPos.y - this.startTouchPos.y;
                    let direction: string;

                    if (Math.abs(dx) > Math.abs(dy)) {
                        direction = dx > 0 ? 'Right' : 'Left';
                    } else {
                        direction = dy > 0 ? 'Up' : 'Down';
                    }

                    console.log(`玩家在指定区域内向 ${direction} 方向进行了滑动操作`);
                    this.cleanup();
                    this.resolve();
                }
            }
        }
        this.startTouchPos = null;
    }

    private isInRange(point: Vec3, start: Vec3, end: Vec3): boolean {
        const padding = 1000;
        const minX = Math.min(start.x, end.x) - padding;
        const maxX = Math.max(start.x, end.x) + padding;
        const minY = Math.min(start.y, end.y) - padding;
        const maxY = Math.max(start.y, end.y) + padding;

        return point.x >= minX && point.x <= maxX && point.y >= minY && point.y <= maxY;
    }

    private drawRangeDisplay() {
        this.rangeDisplayNode = new Node("RangeDisplay");
        const uiTransform = this.rangeDisplayNode.addComponent(UITransform);
        const sprite = this.rangeDisplayNode.addComponent(Sprite);
        sprite.color = new Color(0, 255, 0, 100); // 设置为半透明绿色

        const padding = 100;
        const minX = Math.min(this.startPos.x, this.endPos.x) - padding;
        const maxX = Math.max(this.startPos.x, this.endPos.x) + padding;
        const minY = Math.min(this.startPos.y, this.endPos.y) - padding;
        const maxY = Math.max(this.startPos.y, this.endPos.y) + padding;

        const width = maxX - minX;
        const height = maxY - minY;
        uiTransform.setContentSize(width, height);
        this.rangeDisplayNode.setPosition(minX + width / 2, minY + height / 2);

        this.guideNode.getParent()?.addChild(this.rangeDisplayNode);
    }

    private cleanup() {
        clearTimeout(this.timeoutId);
        this.curTween?.stop();
        if (this.touchListenerNode) {
            this.touchListenerNode.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
            this.touchListenerNode.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
            this.touchListenerNode.destroy();
            this.touchListenerNode = null;
        }
        if (this.rangeDisplayNode) {
            this.rangeDisplayNode.destroy();
            this.rangeDisplayNode = null;
        }
    }
}